package com.atguigu.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.dao.TravelGroupDao;
import com.atguigu.dao.TravelItemDao;
import com.atguigu.entity.PageResult;
import com.atguigu.pojo.TravelGroup;
import com.atguigu.service.TravelGroupService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = TravelGroupService.class)
@Transactional
public class TravelGroupServiceImpl implements TravelGroupService {
    @Autowired
    private TravelGroupDao travelGroupDao;

    @Override
    public void add(TravelGroup travelGroup, Integer[] travelItemIds) {
   //添加跟团游
        travelGroupDao.add(travelGroup);//主键回填；保存前没有id属性值，保存后mybatis框架会将数据分配主键赋值给id属性
        //添加中间表关系数据
        Integer travelGroupId=travelGroup.getId();
        setTravelGroupAndTravelItem(travelGroupId,travelItemIds);//定义一个私有的帮忙方法完成数据保存
    }

    private void setTravelGroupAndTravelItem(Integer travelGroupId,Integer[] travelItemIds) {//以后有可能会共用这个数据
        if(travelItemIds!=null && travelItemIds.length>0){
            for (Integer travelItemId : travelItemIds) {
                Map<String,Integer> map=new HashMap<>();
                map.put("travelGroupId",travelGroupId);
                map.put("travelItemId",travelItemId);
                travelGroupDao.setTravelGroupAndTravelItem(map);
            }

        }
    }

    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage,pageSize);
        Page page=travelGroupDao.findPage(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public TravelGroup get(Integer id) {
        return travelGroupDao.get(id);
    }

    @Override
    public List<Integer> getTravelItemIdByTravelGroupId(Integer travelGroupId) {
        return travelGroupDao.getTravelItemIdByTravelGroupId(travelGroupId);
    }

    @Override
    public void edit(TravelGroup travelGroup, Integer[] travelItemIds) {
        travelGroupDao.edit(travelGroup);
        //先删除中间表信息
        travelGroupDao.deleteByTravelGroupId(travelGroup.getId());
        //再增加新的一批关系
        setTravelGroupAndTravelItem(travelGroup.getId(),travelItemIds);
    }

    @Override
    public void delete(Integer id) {
        int count=travelGroupDao.findTravelGroupById(id);//从中间表查找关联数据，如果存在就不进行删除
        if(count>0){//存在关联数据
            throw new RuntimeException("存在关联数据，无法删除，请先解除关系在进行删除");
        }
        travelGroupDao.delete(id);
    }

    @Override
    public List<TravelGroup> findAll() {
        return travelGroupDao.findAll();
    }
}
